const http = require('http');
const WebSocket = require('ws');

class Test1000Simple {
    constructor() {
        this.token = null;
        this.userId = null;
        this.ws = null;
        this.characters = [];
        this.selectedCharacter = null;
    }

    async runTest() {
        console.log('🚀 开始测试1000指令属性点修复...\n');

        try {
            await this.testHttpLogin();
            await this.testWebSocketConnection();
            await this.testQueryCharacters();
            
            if (this.characters.length === 0) {
                console.log('❌ 没有找到角色，无法继续测试');
                return;
            }

            await this.testSelectCharacter();
            await this.test1000Command();
            
        } catch (error) {
            console.error('❌ 测试失败:', error.message);
        } finally {
            await this.disconnect();
        }
    }

    async testHttpLogin() {
        return new Promise((resolve, reject) => {
            console.log('🔐 开始HTTP登录...');
            
            // 先尝试注册用户
            const registerData = JSON.stringify({
                mobile: '17091271111',
                pwd: '123456',
                captcha: '1234'
            });

            const registerOptions = {
                hostname: 'localhost',
                port: 3000,
                path: '/user-service/user/register',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Content-Length': Buffer.byteLength(registerData)
                }
            };

            const registerReq = http.request(registerOptions, (res) => {
                let data = '';
                res.on('data', (chunk) => {
                    data += chunk;
                });
                res.on('end', () => {
                    try {
                        const response = JSON.parse(data);
                        console.log('📝 用户注册结果:', response);
                        
                        // 无论注册成功还是失败，都尝试登录
                        this.performLogin(resolve, reject);
                    } catch (error) {
                        console.log('❌ 解析注册响应失败:', error.message);
                        this.performLogin(resolve, reject);
                    }
                });
            });

            registerReq.on('error', (error) => {
                console.log('❌ 注册请求失败:', error.message);
                this.performLogin(resolve, reject);
            });

            registerReq.write(registerData);
            registerReq.end();
        });
    }

    performLogin(resolve, reject) {
        const loginData = JSON.stringify({
            mobile: '17091271111',
            pwd: '123456'
        });

        const loginOptions = {
            hostname: 'localhost',
            port: 3000,
            path: '/user-service/user/login',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Content-Length': Buffer.byteLength(loginData)
            }
        };

        const loginReq = http.request(loginOptions, (res) => {
            let data = '';
            res.on('data', (chunk) => {
                data += chunk;
            });
            res.on('end', () => {
                try {
                    const response = JSON.parse(data);
                    if (response.code === 0) {
                        this.token = response.data.accessToken;
                        this.userId = response.data.userId;
                        console.log('✅ HTTP登录成功');
                        resolve();
                    } else {
                        console.log('❌ HTTP登录失败:', response.msg);
                        reject(new Error(response.msg));
                    }
                } catch (error) {
                    console.log('❌ 解析登录响应失败:', error.message);
                    reject(error);
                }
            });
        });

        loginReq.on('error', (error) => {
            console.log('❌ HTTP请求失败:', error.message);
            reject(error);
        });

        loginReq.write(loginData);
        loginReq.end();
    }

    async testWebSocketConnection() {
        return new Promise((resolve, reject) => {
            console.log('🔌 建立WebSocket连接...');
            
            this.ws = new WebSocket('ws://localhost:3000/user-service/websocket');
            
            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });
            
            this.ws.on('error', (error) => {
                console.log('❌ WebSocket连接失败:', error.message);
                reject(error);
            });
        });
    }

    async testQueryCharacters() {
        return new Promise((resolve) => {
            console.log('👥 查询角色列表...');
            
            const responseHandler = (message) => {
                try {
                    const data = JSON.parse(message.toString());
                    if (data.act_id === 3) {
                        this.ws.removeListener('message', responseHandler);
                        
                        if (data.code === 0) {
                            this.characters = data.roleList || [];
                            console.log(`✅ 找到 ${this.characters.length} 个角色`);
                            resolve();
                        } else {
                            console.log('❌ 查询角色失败:', data.msg);
                            resolve();
                        }
                    }
                } catch (error) {
                    console.log('❌ 解析角色列表响应失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    resolve();
                }
            };
            
            this.ws.on('message', responseHandler);
            
            // 发送查询角色请求
            this.ws.send(JSON.stringify({
                c: 3,
                d: {}
            }));
            
            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                console.log('⏰ 查询角色超时');
                resolve();
            }, 5000);
        });
    }

    async testSelectCharacter() {
        return new Promise((resolve) => {
            if (this.characters.length === 0) {
                console.log('❌ 没有角色可选择');
                resolve();
                return;
            }

            console.log('🎯 选择角色...');
            this.selectedCharacter = this.characters[0];
            
            const responseHandler = (message) => {
                try {
                    const data = JSON.parse(message.toString());
                    if (data.act_id === 4) {
                        this.ws.removeListener('message', responseHandler);
                        
                        if (data.code === 0) {
                            console.log(`✅ 选择角色成功: ${this.selectedCharacter.name}`);
                            resolve();
                        } else {
                            console.log('❌ 选择角色失败:', data.msg);
                            resolve();
                        }
                    }
                } catch (error) {
                    console.log('❌ 解析选择角色响应失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    resolve();
                }
            };
            
            this.ws.on('message', responseHandler);
            
            // 发送选择角色请求
            this.ws.send(JSON.stringify({
                c: 4,
                d: { id: this.selectedCharacter.id }
            }));
            
            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                console.log('⏰ 选择角色超时');
                resolve();
            }, 5000);
        });
    }

    async test1000Command() {
        return new Promise((resolve) => {
            console.log('📊 测试1000指令（角色信息）...');
            
            const responseHandler = (message) => {
                try {
                    const data = JSON.parse(message.toString());
                    if (data.act_id === 1000) {
                        this.ws.removeListener('message', responseHandler);
                        
                        if (data.code === 0) {
                            console.log('✅ 1000指令执行成功');
                            console.log('📊 角色信息:');
                            console.log(`   角色ID: ${data.data.id}`);
                            console.log(`   角色名: ${data.data.name}`);
                            console.log(`   等级: ${data.data.lvl}`);
                            console.log(`   经验: ${data.data.exp}`);
                            console.log(`   攻击力(ap): ${data.data.ap}`);
                            console.log(`   生命值(hp): ${data.data.hp}`);
                            console.log(`   法力值(mp): ${data.data.mp}`);
                            console.log(`   速度(sp): ${data.data.sp}`);
                            console.log(`   防御力(df): ${data.data.df}`);
                            console.log(`   负重(weight): ${data.data.weight}`);
                            console.log('');
                            console.log('🎯 属性点信息:');
                            console.log(`   已分配力量(app): ${data.data.app}`);
                            console.log(`   已分配体质(hpp): ${data.data.hpp}`);
                            console.log(`   已分配智力(mpp): ${data.data.mpp}`);
                            console.log(`   已分配敏捷(spp): ${data.data.spp}`);
                            console.log(`   剩余可分配点数(p): ${data.data.p}`);
                            
                            // 验证属性点逻辑
                            const level = data.data.lvl;
                            const totalPoints = (level - 1) * 4; // 每级4点
                            const usedPoints = data.data.app + data.data.hpp + data.data.mpp + data.data.spp;
                            const availablePoints = data.data.p;
                            const calculatedTotal = usedPoints + availablePoints;
                            
                            console.log('');
                            console.log('🔍 属性点验证:');
                            console.log(`   等级: ${level}`);
                            console.log(`   应有总点数: ${totalPoints} (每级4点)`);
                            console.log(`   已使用点数: ${usedPoints}`);
                            console.log(`   剩余点数: ${availablePoints}`);
                            console.log(`   实际总点数: ${calculatedTotal}`);
                            
                            // 验证每种属性是否至少为等级数
                            const minPoints = level;
                            const strengthValid = data.data.app >= minPoints;
                            const constitutionValid = data.data.hpp >= minPoints;
                            const intelligenceValid = data.data.mpp >= minPoints;
                            const agilityValid = data.data.spp >= minPoints;
                            
                            console.log('');
                            console.log('✅ 属性点最低值验证:');
                            console.log(`   力量 >= 等级: ${strengthValid} (${data.data.app} >= ${minPoints})`);
                            console.log(`   体质 >= 等级: ${constitutionValid} (${data.data.hpp} >= ${minPoints})`);
                            console.log(`   智力 >= 等级: ${intelligenceValid} (${data.data.mpp} >= ${minPoints})`);
                            console.log(`   敏捷 >= 等级: ${agilityValid} (${data.data.spp} >= ${minPoints})`);
                            
                            const allValid = strengthValid && constitutionValid && intelligenceValid && agilityValid;
                            const pointsValid = calculatedTotal === totalPoints;
                            
                            console.log('');
                            console.log('🎉 验证结果:');
                            console.log(`   属性点计算: ${pointsValid ? '✅ 正确' : '❌ 错误'}`);
                            console.log(`   最低值保证: ${allValid ? '✅ 正确' : '❌ 错误'}`);
                            console.log(`   总体状态: ${pointsValid && allValid ? '🎉 完全正确' : '⚠️ 需要修复'}`);
                            
                        } else {
                            console.log('❌ 1000指令执行失败:', data.msg);
                        }
                        resolve();
                    }
                } catch (error) {
                    console.log('❌ 解析1000指令响应失败:', error.message);
                    this.ws.removeListener('message', responseHandler);
                    resolve();
                }
            };
            
            this.ws.on('message', responseHandler);
            
            // 发送1000指令请求
            this.ws.send(JSON.stringify({
                c: 1000,
                d: {}
            }));
            
            // 设置超时
            setTimeout(() => {
                this.ws.removeListener('message', responseHandler);
                console.log('⏰ 1000指令超时');
                resolve();
            }, 5000);
        });
    }

    async disconnect() {
        if (this.ws) {
            this.ws.close();
            console.log('✅ WebSocket连接已关闭');
        }
    }
}

// 主执行函数
async function main() {
    const tester = new Test1000Simple();
    await tester.runTest();
}

// 如果直接运行此脚本
if (require.main === module) {
    main();
}

module.exports = Test1000Simple;
